package com.mazaiting.web.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.exceptions.EmptyObjectException;

import java.util.List;

/**
 * 用户工具类
 */
public class UserUtil {

    /**
     * 解析JWT获取用户ID
     *
     * @return 用户 ID
     */
    public static Long getUserId() throws EmptyObjectException {
        return JwtUtil
                .getPayloadInfo()
                .orElseThrow(() -> new EmptyObjectException(ResultCode.ACCESS_UNAUTHORIZED))
                .getUserId();
    }

    /**
     * 解析JWT获取部门ID
     *
     * @return 部门 ID
     */
    public static Long getDeptId() throws EmptyObjectException {
        return JwtUtil
                .getPayloadInfo()
                .orElseThrow(() -> new EmptyObjectException(ResultCode.ACCESS_UNAUTHORIZED))
                .getDeptId();
    }

    /**
     * 解析JWT获取获取用户名
     *
     * @return 用户名
     */
    public static String getUsername() throws EmptyObjectException {
        return JwtUtil
                .getPayloadInfo()
                .orElseThrow(() -> new EmptyObjectException(ResultCode.ACCESS_UNAUTHORIZED))
                .getUsername();
    }


    /**
     * JWT获取用户角色列表
     *
     * @return 角色列表
     */
    public static List<String> getRoles() throws EmptyObjectException {
        return JwtUtil
                .getPayloadInfo()
                .orElseThrow(() -> new EmptyObjectException(ResultCode.ACCESS_UNAUTHORIZED))
                .getAuthorities();
    }

    /**
     * 是否「超级管理员」
     *
     * @return true: 超级管理员; false: 非超级管理员
     */
    public static boolean isRoot() throws EmptyObjectException {
        List<String> roles = getRoles();
        return CollectionUtil.isNotEmpty(roles) && roles.contains(SecurityConst.ROLE_ROOT_CODE);
    }
}
